$(function(){
	//右侧画布的数据数组
	canvasData = [];
	//绘制左侧的控件区域
	drawLeft();
	//右侧画布
	rightCvs = document.getElementById('canvasRight');
	rightCtx = rightCvs.getContext('2d');
	tdDraw = new TDrawCanvas(rightCvs);
	//画布的鼠标划过
	canvasRight.ondragover = function(ev){
		canvasOverFun(ev);
	};
	//画布的鼠标拖拽的放下键
	canvasRight.ondrop = function(ev){
		canvasDropFun(ev);
	};
	//画布上的鼠标拖拽
	canvasRight.onmousedown = function(ev){
		canvasDragFun(ev);
	};
});

function drawLeft(){
	var controlCellList = '';
	var controlNameList = ['循环','分支'];
	for(var j = 0;j<2;j++){
		controlCellList = controlCellList+"<a draggable='true' class='controllListCell' name='"+controlNameList[j]+"' elementid='"+j+"'>"+controlNameList[j]+"</a>";
	}
	$('#controlList').html(controlCellList);
	//每个控件都开始拖拽事件，并添加拖动的数据
	var controlCount = $('#controlList').find('a').length;
	for(var i = 0;i<controlCount;i++){
		$('#controlList').find('a')[i].ondragstart = function(ev){
			ev.dataTransfer.setData('elementid',ev.target.attributes['elementid'].value);
			ev.dataTransfer.setData('name',ev.currentTarget.name);
		}
	}
}
function canvasOverFun(ev){
	var x = ev.offsetX;
	var y = ev.offsetY;
	
	if(x>0 && x<rightCvs.width){
		ev.dataTransfer.dropEffect = 'move';
	}else{
		ev.dataTransfer.dropEffect = 'none';
	}
	ev.stopPropagation();
	ev.preventDefault();
}

function canvasDropFun(ev){
	var x = ev.offsetX;
	var y = ev.offsetY;
	console.log("("+x+","+y+")");
	ev.preventDefault();
	console.log(ev.dataTransfer.getData("name"));
	
	var selectObj = getSelectElement(x,y);
	if(!selectObj){
		var loopCell = tdDraw.getDrawing('loop',
		{
			x:x,y:y,width:100,height:100,isLabel:true,filledColor:'#77bf1b',
			label:{value:ev.dataTransfer.getData("name"),point:{x:x,y:y+25},fontColor:'#ffffff'}
		});
		loopCell.draw();
		canvasData.push({x:x,y:y,width:100,height:100});
	}else{
		rightCtx.clearRect(0,0,rightCvs.width,rightCvs.height);
		var loopCell = tdDraw.getDrawing('loop',
		{
			x:selectObj.x,y:selectObj.y,width:100 + 20,height:100 + 30 + 100 - 70,isLabel:true,filledColor:'#77bf1b',
			label:{value:ev.dataTransfer.getData("name"),point:{x:selectObj.x,y:selectObj.y+25},fontColor:'#ffffff'}
		});
		loopCell.draw();
		var loopCell1 = tdDraw.getDrawing('loop',
		{
			x:(selectObj.x + 10),y:(selectObj.y + 45),width:100,height:100,isLabel:true,filledColor:'#77bf1b',
			label:{value:ev.dataTransfer.getData("name"),point:{x:selectObj.x + 10,y:selectObj.y + 45+25},fontColor:'#ffffff'}
		});
		loopCell1.draw();
	}
	
}
function canvasDragFun(ev){
	ev.preventDefault();
	var x = ev.offsetX;
	var y = ev.offsetY;
	
	getSelectElement();
}

function getSelectElement(x,y){
	var selectObj = null;
	for(var i = 0;i<canvasData.length;i++){
		if(x>canvasData[i].x && x < (canvasData[i].x+canvasData[i].width)
		&& y>canvasData[i].y && y<(canvasData[i].y + canvasData[i].height)){
			selectObj = canvasData[i];
		}
	}
	return selectObj;
}

function reDraw(){
	
}
